package com.hxci.pointmap.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxci.pointmap.dao.DevDAO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

public class DevService {
    private DevDAO devDAO = new DevDAO();

    public DevDAO getDevDAO() {
        return devDAO;
    }

    public void doAddDev(HttpServletRequest req, HttpServletResponse resp) {
        // 检查是否是AJAX请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) ||
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            Part part = req.getPart("devIcon");
            String iconDir = "C:\\upload\\dev\\";
            String iconFile = "dev_"+sdf.format(date)+".png";
            
            // 获取前端传递的图标名称
            String iconName = req.getParameter("iconName");
            if (iconName != null && !iconName.isEmpty()) {
                // 使用前端选择的图标名称
                iconFile = iconName;
                System.out.println("使用选择的图标: " + iconFile);
            } else if (part != null && part.getSize() > 0) {
                // 只有当用户上传了图标时才保存文件
                System.out.println("file = " + iconDir+iconFile);
                part.write(iconDir+iconFile);
            } else {
                // 如果没有上传图标也没有选择图标，使用默认图标
                iconFile = "default.png";
                System.out.println("使用默认图标: " + iconFile);
            }

            List parmList = new ArrayList();
            parmList.add(req.getParameter("devName"));
            parmList.add(req.getParameter("devType"));//devType
            parmList.add(req.getParameter("lon"));
            parmList.add(req.getParameter("lat"));
            parmList.add(req.getParameter("isValid"));
            parmList.add(iconFile);
            int result = devDAO.insertDev(parmList);

            // 如果是AJAX请求，返回JSON格式数据
            if (isAjax) {
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");

                Map<String, Object> responseResult = new HashMap<>();
                if (result > 0) {
                    responseResult.put("success", true);
                    responseResult.put("message", "设备添加成功");
                } else {
                    responseResult.put("success", false);
                    responseResult.put("message", "设备添加失败");
                }

                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.writeValue(resp.getWriter(), responseResult);
            } else {
                if(result > 0) {
                    req.getRequestDispatcher("deviceManagement.jsp").forward(req, resp);
                } else {
                    PrintWriter out = resp.getWriter();
                    out.print("添加失败");
                }
            }
        }catch (Exception e){
            e.printStackTrace();

            // 如果是AJAX请求，返回错误信息
            if (isAjax) {
                try {
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding("UTF-8");

                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("success", false);
                    errorResult.put("message", "添加设备时发生错误: " + e.getMessage());

                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.writeValue(resp.getWriter(), errorResult);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public void doQueryDev(HttpServletRequest req, HttpServletResponse resp) {
        // 检查是否是AJAX请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) || 
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        List<Object> parmList = new ArrayList();
        String devName = req.getParameter("devName");
        String devType = req.getParameter("devType");
        if(devName == null){
            devName="";
        }
        int currentPage = 1;
        int pageSize = 5;
        int totalCount = 0;
        int startIdx = 0;
        String currentPageStr = req.getParameter("currentPage");
        System.out.println("currentPageStr = "+currentPageStr);

        if (currentPageStr == null || currentPageStr.equals("")||currentPageStr.equals("null") ){
            currentPageStr = 1+"";
        }
        currentPage = Integer.parseInt(currentPageStr);
        String queryType = req.getParameter("queryType");
        if (queryType == null || queryType.equals("")||queryType.equals("null") ){
            queryType = 1+"";
        }
        System.out.println("queryType = "+queryType);
        if(queryType.equals("1")){
            currentPage = 1;
            startIdx = 0;
        }
        if(queryType.equals("2")){
            currentPage = currentPage -1;
            startIdx = (currentPage-1)*pageSize;
            System.out.println("currentPage = "+currentPage);
            System.out.println("startIdx = "+startIdx);
        }
        if(queryType.equals("3")){
            currentPage = currentPage +1;
            startIdx = (currentPage-1) * pageSize;
        }


        System.out.println("currentPage = "+currentPage);
        System.out.println("startIdx = "+startIdx);



        String sql = " SELECT " +
                " * " +
                " FROM " +
                " device_info t " +
                " WHERE " +
                "  t.dev_name LIKE '%"+devName+"%'   ";
        if(devType!=null && !devType.equals("")){
            sql = sql+"   AND t.dev_type = '"+devType+"' ";
        }

        String countSQL = "select count(1) cnt from ( "+sql+" ) tab " ;
        List<Map<String,Object>> countList = devDAO.queryDevList(countSQL,parmList);
        String totalCountStr = countList.get(0).get("cnt").toString();
        totalCount = Integer.parseInt(totalCountStr);
        if(queryType.equals("4")) {
            currentPage = (totalCount%pageSize==0)?totalCount / pageSize : totalCount / pageSize + 1;
            startIdx = (currentPage-1) * pageSize;
        }
        
        // 处理直接跳转到指定页的情况
        if(queryType.equals("5")) {
            // 使用currentPageStr中指定的页码
            currentPage = Integer.parseInt(currentPageStr);
            // 验证页码的有效性
            int totalPages = (totalCount%pageSize==0)?totalCount / pageSize : totalCount / pageSize + 1;
            if(currentPage < 1) {
                currentPage = 1;
            } else if(currentPage > totalPages) {
                currentPage = totalPages;
            }
            startIdx = (currentPage-1) * pageSize;
        }

        sql = sql+" LIMIT "+startIdx+","+pageSize;
        System.out.println("countSQL = "+ countSQL);
        System.out.println("sql = "+ sql);

        List<Map<String,Object>> resultList =devDAO.queryDevList(sql,parmList);
        req.setAttribute("resultList",resultList);
        System.out.println("resultList = "+resultList);
        req.setAttribute("currentPage",currentPage+"");
        System.out.println("currentPage = "+currentPage);
        req.setAttribute("totalCount", totalCount);
        System.out.println("totalCount = "+totalCount);


        // 如果是AJAX请求，不进行页面转发
        if (isAjax) {
            return;
        }

        try {
            req.getRequestDispatcher("query_list.jsp").forward(req, resp);
        }catch(ServletException e){
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void doUpdateDev(HttpServletRequest req, HttpServletResponse resp) {
        // 检查是否是AJAX请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) ||
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        List parmList = new ArrayList();
        String devId = req.getParameter("devId");
        parmList.add(devId);
        List<Map<String, Object>>mapList = devDAO.queryDevById(parmList);

        // 如果查询结果为空，返回错误信息
        if (mapList == null || mapList.isEmpty()) {
            try {
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("UTF-8");
                PrintWriter out = resp.getWriter();
                out.println("<script>");
                out.println("alert('设备不存在或已被删除');");
                out.println("window.location.href='deviceManagement.jsp';");
                out.println("</script>");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        req.setAttribute("devInfo",mapList);
        try {
            req.getRequestDispatcher("dev_edit.jsp").forward(req, resp);
        } catch (ServletException e){
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void doDeleteDev(HttpServletRequest req, HttpServletResponse resp) {
        // 检查是否是AJAX请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) || 
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        try {
            List parmList = new ArrayList();
            String devId = req.getParameter("devId");
            parmList.add(devId);
            int result = devDAO.deleteDev(parmList);

            // 如果是AJAX请求，不进行页面转发
            if (isAjax) {
                return;
            }

            if (result > 0) {
                req.getRequestDispatcher("query_list.jsp").forward(req, resp);
            } else {
                PrintWriter out = resp.getWriter();
                out.print("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateDev(HttpServletRequest req, HttpServletResponse resp) {
        // 检查是否是AJAX请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader) ||
                        req.getParameter("format") != null && "json".equals(req.getParameter("format"));

        List parmList = new ArrayList();
        parmList.add(req.getParameter("devName"));
        parmList.add(req.getParameter("devType"));//devType
        parmList.add(req.getParameter("lon"));
        parmList.add(req.getParameter("lat"));
        parmList.add(req.getParameter("isValid"));
        parmList.add(req.getParameter("iconName"));
        parmList.add(req.getParameter("devId"));
        int result = devDAO.updateDev(parmList);

        // 如果是AJAX请求，返回JSON格式数据
        if (isAjax) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");

            Map<String, Object> responseResult = new HashMap<>();
            if (result > 0) {
                responseResult.put("success", true);
                responseResult.put("message", "设备更新成功");
            } else {
                responseResult.put("success", false);
                responseResult.put("message", "设备更新失败");
            }

            ObjectMapper objectMapper = new ObjectMapper();
            try {
                objectMapper.writeValue(resp.getWriter(), responseResult);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            doQueryDev(req, resp);
        }
    }


}
